package com.trainfinder.proxy;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.Socket;


public class RemoteSocketProvider {

	private final Socket remoteSocket;

	public RemoteSocketProvider(BufferedInputStream inputStream)
			throws ServerCreationException {

		try {
			remoteSocket = new Socket(getDomain(inputStream), 80);

		} catch (IOException e1) {
			throw new ServerCreationException(e1);
		}
	}

	private String getDomain(String data) {
		String result = "";
		int start = data.indexOf("http://");
		if (start != -1) {
			int end = data.indexOf("/", start + "http://".length());
			if (end != -1) {
				result = data.substring(start + "http://".length(), end);
			}
		}
		return result;
	}

	private String getDomain(BufferedInputStream inputStream) {

		byte[] bytes = new byte[1024];
		inputStream.mark(bytes.length);
		StringBuffer buffer = new StringBuffer();
		try {

			int i;
			int forwardSlashCount = 0;
			for (; (i = inputStream.read()) != -1;) {

				buffer.append((char) i);
				if (i == '/') {
					forwardSlashCount++;
					if (forwardSlashCount == 3) {
						break;
					}
				}
			}
			inputStream.reset();
		} catch (IOException e) {
			// e.printStackTrace();
		}

		final String result = getDomain(buffer.toString());
		return result;
	}


	public Socket getRemoteSocket() {
		return remoteSocket;
	}

}
